#!/bin/env python
#comment: used to check nginx log for zabbix
#date:    2014-12-09
#author:  sixther.me
# -*- coding: utf-8 -*-

import time,sys,re

clickstream_log_df=open('/var/www/vhosts/www.lightinthebox.com/logs/clickstream.log')
time_ymd=time.strftime('%Y-%m-%d',time.localtime(time.time()))
becur=time.time() - 300

clickstream_log_list=clickstream_log_df.readlines()
clickstream_log_df.close()
clickstream_log_list.reverse()

def get_http_code_account(code):
        http_code_account=[]
        ddrequest_time=0
        for i in clickstream_log_list:
                i_string=i.split('[',1)[1].strip().replace(':',' ')
                timestr=time_ymd + ' ' + i_string.split()[1] + ':' +  i_string.split()[2] + ':' + i_string.split()[3]
                timestamp=time.mktime(time.strptime(timestr, "%Y-%m-%d %H:%M:%S"))
                if int(timestamp) >= int(becur):
                        http_code=i_string.split()[8]
                        http_code_account.append(http_code)
                else:
                        break
        if code == 'total':
                return len(http_code_account)
        else:
                return http_code_account.count(code)
def get_avg_response_time():
        request_time=0
        n=0
        p=re.compile("(\d+)\.(\d*)")
        for i in clickstream_log_list:
                i_string=i.split('[',1)[1].strip().replace(':',' ')
                timestr=time_ymd + ' ' + i_string.split()[1] + ':' +  i_string.split()[2] + ':' + i_string.split()[3]
                timestamp=time.mktime(time.strptime(timestr, "%Y-%m-%d %H:%M:%S"))
                if int(timestamp) >= int(becur):
                        n += 1
                        s=p.search(i_string.split()[-3])
                        if s:
                                request_time = request_time + float(i_string.split()[-3])
        return ("%.3f" % (request_time / n))
if __name__ == '__main__':
        status_data_array={
                '200' : 'get_http_code_account(\'200\')',
                '302' : 'get_http_code_account(\'302\')',
                '403' : 'get_http_code_account(\'403\')',
                '404' : 'get_http_code_account(\'404\')',
                '502' : 'get_http_code_account(\'502\')',
                '503' : 'get_http_code_account(\'503\')',
                'total' : 'get_http_code_account(\'total\')',
                'avg_response_time' : 'get_avg_response_time()'
        }
        print eval(status_data_array[sys.argv[1]])
